<template>
  <div class="page-controller">
    <!-- 查询条件区 -->
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      v-model:form-value="state.query"
      :table-column="columns"
      :defaultFormNum="13"
      :excludeValues="['taskArriveTime', 'beginTime']"
      :wrapperSpan="wrapperSpan"
      @submit="searchFn"
      @reset="() => (state.query.beginTime = null)"
    >
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem class="date-range-class" name="taskArriveTime" label="任务到达时间">
          <FIDatePicker
            value-format="YYYYMMDD"
            v-model="state.query.beginTime"
            placeholder="请选择"
            :disabled-date="disabledBeginDate"
          />
          <FIDatePicker
            value-format="YYYYMMDD"
            v-model="state.query.endTime"
            placeholder="请选择"
            :disabled-date="disabledEndDate"
          />
        </FIFormItem>
        <!-- <FIFormItem name="taskArriveTime" label="任务到达时间">
          <FIDatePicker value-format="YYYYMMDD" v-model="state.query.taskArriveTime" type="daterange" start-placeholder="" end-placeholder="" />
        </FIFormItem> -->
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="processDefKey" label="流程名称">
          <ProcessName v-model="state.query.processDefKey" />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="taskDefKey" label="任务名称">
          <TaskName v-model="state.query.taskDefKey" />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="taskStatus" label="任务状态">
          <FISelect
            v-model="state.query.taskStatus"
            valueCustom="value"
            :options="[
              { value: 'completed', label: '已完成' },
              { value: 'completed_return', label: '回退完成' },
              { value: 'closed', label: '已关闭' },
            ]"
            clearable
          />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="starter" label="流程发起人">
          <FISelect
            v-model="state.query.starter"
            valueCustom="loginName"
            :props="{ value: 'loginName', label: 'userCName' }"
            :options="allStarterArr"
            :display-key="['loginName', 'userCName']"
            filterable
          >
          </FISelect>
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="startDeptId" label="发起部门">
          <DeptTree v-model="state.query.startDeptId" />
          <!-- <FISelect
            v-model="state.query.startDeptId"
            valueCustom="groupEname"
            :props="{ value: 'groupEname', label: 'groupCname' }"
            :options="allDeptArr"
            clearable
          /> -->
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="productNo" label="产品号">
          <FIInput v-model="state.query.productNo" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="productName" label="产品名称">
          <FIInput v-model="state.query.productName" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="projectNo" label="项目号">
          <FIInput v-model="state.query.projectNo" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="projectName" label="项目名称">
          <FIInput v-model="state.query.projectName" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="contractNo" label="合同号">
          <FIInput v-model="state.query.contractNo" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="contractName" label="合同名称">
          <FIInput v-model="state.query.contractName" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="instSubject" label="业务说明">
          <FIInput v-model="state.query.instSubject" clearable />
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <!-- 查询结果列表区 -->
    <FITable
      ref="tableRef"
      class="box-radius2 margin-top20"
      title="记录集"
      :id="`result_${tableId}`"
      :data="state.dataList"
      primaryKey="id"
      v-model:columns="columns"
      :isLoading="isTableLoading"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      :showSaveModel="false"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @action-click="handleActionClick"
    >
      <!-- 自定义列 moduleEname1 -->
      <!-- <template #manage="{ scope }">
        <FIButton border size="small">查看</FIButton>
        <FIButton border size="small">图形监控</FIButton>
      </template>
      <template #his="{ scope }">
        <FIButton border size="small">查看</FIButton>
      </template> -->
      <template #headerBtn>
        <FIButton id="export" :loading="exportLoading" type="primary" @click="exportClick">导出</FIButton>
      </template>
    </FITable>
    <HisDialog
      :visible="hisDialogVisible"
      :task-id="hisTaskId"
      @update:visible="(newValue) => (hisDialogVisible = newValue)"
    ></HisDialog>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'
import FIDatePicker from '@/components/FIDatePicker.vue'
import DeptTree from '../../components/DeptTree.vue'
import ProcessName from '../../components/ProcessName.vue'
import TaskName from '../../components/TaskName.vue'
import HisDialog from '../../components/HisDialog.vue'

import { apiQueryUser, apiQueryDept, apiMyDoneTaskExport } from '@/api/modules/EWPT.js'
import { apiRequestPost } from '@/api/globalApi.js'
import { useMessage } from '@/hooks/message' // 通用message消息提示框
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData, openUrlFn, useRouteNavigation } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import { getCurrentInstance } from 'vue'
import FIButton from '@/components/FIButton.vue'
const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
// 路由对象
const route = useRoute()
// el-col span栅格占据的列数
const wrapperSpan = 8
// 表格是否显示加载中
const isTableLoading = ref(false)
// 页面编码
const tableId = 'MyDoneTask'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
// 表格对象
const tableRef = ref(null)
const state = reactive({
  // 查询条件
  query: {
    taskArriveTime: '', // 任务到达时间
    processDefKey: '', // 流程名称
    beginTime: null, // 任务到达开始时间'
    endTime: null, // 任务到达结束时间
    taskDefKey: '', // 任务名称
    taskStatus: 'completed', // 任务状态 默认 completed:已完成
    starter: '', // 流程发起人
    startDeptId: '', // 发起部门
    productNo: '', // 产品号
    productName: '', // 产品名称
    projectNo: '', // 项目号
    projectName: '', // 项目名称
    contractNo: '', // 合同号
    contractName: '', // 合同名称
    instSubject: '', // 业务说明
    current: 1,
    size: 10,
  },
  // 表格数据
  dataList: [],
})
const hisDialogVisible = ref(false)
const hisTaskId = ref('')
// 页面配置
const pageConfig: PageConfig = reactive({
  total: 0, // 总条数
  currentPage: 1, // 当前页码
})
// 表格列数据
const columns: Column[] = reactive([
  {
    label: '业务说明',
    prop: 'subject',
    align: 'center',
    width: '260',
  },
  {
    label: '流程名',
    prop: 'processName',
    align: 'center',
    width: '150',
  },
  {
    label: '节点名',
    prop: 'name',
    align: 'center',
    width: '150',
    editType: 'input',
  },
  {
    label: '发起人',
    prop: 'starterName',
    align: 'center',
    width: '150',
    editType: 'input',
  },
  {
    label: '发起部门',
    prop: 'startDeptName',
    align: 'center',
    width: '150',
    editType: 'input',
  },
  {
    label: '到达时间',
    prop: 'startTime',
    align: 'center',
    width: '160',
    editType: 'date-picker',
  },
  // {
  //   label: '任务链接',
  //   prop: 'manage',
  //   align: 'center',
  //   width: '250',
  // },
  {
    label: '任务状态',
    prop: 'taskStatusName',
    align: 'center',
    width: '120',
  },
  {
    label: '产品名称',
    prop: 'productName',
    align: 'center',
    width: '150',
  },
  {
    label: '产品分期名称',
    prop: 'prodPeriodName',
    align: 'center',
    width: '150',
  },
  {
    label: '项目名称',
    prop: 'projectName',
    align: 'center',
    width: '150',
  },
  {
    label: '合同号',
    prop: 'contractNo',
    align: 'center',
    width: '150',
  },
  {
    label: '领取状态',
    prop: 'claimStatus',
    align: 'center',
    width: '150',
    editType: 'select',
    editConfig: {
      options: [
        // 下拉框选项
        { value: 'false', label: '未领取' },
        { value: 'true', label: '已领取' },
        { value: 'claimed', label: '被领取' },
      ],
    },
  },
  {
    label: '流程状态',
    prop: 'processState',
    align: 'center',
    width: '150',
    editType: 'select',
    editConfig: {
      options: [
        // 下拉框选项
        { value: 'active', label: '正运行' },
        { value: 'suspend', label: '挂起' },
        { value: 'finish', label: '结束' },
        { value: 'manual-finish', label: '终止' },
      ],
    },
  },
  {
    label: '流程ID',
    prop: 'sequenceId',
    align: 'center',
    width: '180',
  },
  {
    label: '执行者',
    prop: 'completerName',
    align: 'center',
    width: '120',
  },
  // {
  //   label: '委托代理履历',
  //   prop: 'his',
  //   align: 'center',
  //   minWidth: '120',
  // },
  {
    label: '',
    prop: 'action',
    actionConfig: [
      { id: 'toTask', type: '查看任务' },
      { id: 'trace', type: '图形监控' },
      { id: 'his', type: '查看委托代理履历' },
    ],
  },
])
// 选中列表集合
const checkedRows = ref([])
// 选中列表集合值改变回调函数
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
// 分页大小改变回调函数
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
// 分页页码改变回调函数
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn()
}
// 搜索查询函数
const searchFn = (type?: string, columnsVal?: any) => {
  // 页面搜索数据组装
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns
  state.query.current = pageConfig.currentPage
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  const apiUrl = proxy.$Button_api('query', route.name)
  apiRequestPost(apiUrl, state.query)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // useMessage().error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
function checkDateDisabled(date, targetTime) {
  if (targetTime) {
    return date > targetTime
  }
  return false
}

const disabledBeginDate = (date) => checkDateDisabled(date, state.query.endTime)
const disabledEndDate = (date) => checkDateDisabled(state.query.beginTime, date)
const { navigateToPage } = useRouteNavigation()
// 操作按钮回调
const handleActionClick = (item, rowData, btnInfo) => {
  // openUrlFn(item.id, rowData)
  if (item.id == 'toTask') {
    // router.push({
    //   name: 'EWTaskFormForwarder',
    //   query: {
    //     processInstanceId: rowData.processInstanceId,
    //     taskId: rowData.id,
    //   },
    // })
    navigateToPage(item.id, rowData)
  } else if (item.id == 'trace') {
    // openUrlFn('trace', rowData)
    navigateToPage(item.id, rowData)
  } else if (item.id == 'his') {
    // openUrlFn('his', rowData)
    hisTaskId.value = rowData.id
    hisDialogVisible.value = true
  }
}
//导出
const exportLoading = ref(false)
const exportClick = () => {
  exportLoading.value = true
  apiMyDoneTaskExport(state.query)
    .then((res) => {
      exportLoading.value = false
      useMessage().success('导出成功')
    })
    .catch(() => {
      exportLoading.value = false
    })
}

// 流程发起人
const allStarterArr = ref([])
// 查询所有流程发起人
const getAllProcessesStarter = () => {
  apiQueryUser().then((res) => {
    if (res.data.success === true) {
      allStarterArr.value = res.data.data || []
    }
  })
}
// 流程发起部门
const allDeptArr = ref([])
// 查询所有流程发起部门
const getAllProcessesDept = () => {
  apiQueryDept().then((res) => {
    if (res.data.success === true) {
      allDeptArr.value = res.data.data || []
    }
  })
}

onMounted(() => {
  getAllProcessesStarter()
  getAllProcessesDept()
  // 获取查询条件缓存
  const { cachedQuery } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  searchFn()
})
</script>
<style lang="less" scoped>
.date-range-class {
  display: flex !important;
  ::v-deep(.el-form-item__content) {
    width: 220px !important;
    display: flex !important;
    justify-content: space-between !important;
    .el-input__prefix {
      display: none !important;
    }
    .el-input {
      width: 107px !important;
    }
  }
}
</style>
